using System;
using System.ComponentModel;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace zevenseas.Community.Web.UI.WebControls
{
    public class SPBoundDateTimeField : SPBoundField
    {
        private readonly CultureInfo _culture;
        private string _dateFormat = "d";

        public SPBoundDateTimeField()
        {
            SPRegionalSettings regionalSettings = SPContext.Current.Web.CurrentUser.RegionalSettings ??
                                                  SPContext.Current.Web.RegionalSettings;

            if (regionalSettings != null)
            {
                _culture = new CultureInfo((int)regionalSettings.LocaleId);
            }
            else
            {
                _culture = CultureInfo.CurrentUICulture;
            }
        }
        public string DateFormat
        {
            get { return _dateFormat; }
            set
            {
                if (string.IsNullOrEmpty(value)) throw new ArgumentNullException("value");
                _dateFormat = value;
            }
        }
        protected override void ChildControlDataBinding(Control childControl, object dataItem,
                                                        MemberDescriptor dataFieldPropertyDescriptor)
        {
            string value = GetPropertyValue(dataItem, dataFieldPropertyDescriptor.Name); Label label = (Label)childControl; DateTime date;
            if (DateTime.TryParse(value, out date))
            {
                label.Text = date.ToString(DateFormat, _culture);
            }
            else
            {
                label.Text = value;
            }
        }
        protected override Control GetChildControlInstance()
        {
            return new Label();
        }
    }
}